package design.mode.model.factory.configfactory.factory;

import design.mode.model.factory.util.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @description 工厂方法改进：简单工厂 + 配置文件
 * @since jdk11
 */
public class SimpConfigureFactory {
    private static Map<String, Object> map = new HashMap<>();

    static {
        Properties properties = new Properties();
        InputStream resourceAsStream = SimpConfigureFactory.class.getClassLoader().getResourceAsStream("bean.properties.bak");
        try {
            assert resourceAsStream != null;
            properties.load(resourceAsStream);
            Set<Object> keys = properties.keySet();
            keys.forEach(key -> {
                String className = (String) properties.get(key);
                try {
                    Class<?> aClass = Class.forName(className);
                    //创建对象
                    map.put((String) key, BeanUtils.getBean(aClass));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取bean对象
     *
     * @param name 类型
     * @return bean对象
     */
    public static Object createCoffee(String name) {
        return map.get(name);
    }
}
